### 根据json 字典中的ROI 对图像进行裁剪 并保存
import json
import numpy as np
import cv2
import os
from shutil import copyfile
def json_dict(json_name):
    f = open(json_name,encoding="utf-8")
    user_dic = json.load(f)
    print(user_dic.keys())
    return user_dic
    # 【1. 获取文件绝对路径】
def _getFilesPath(file_dir):
    filenames = []
    img_name = []
    for root, dirs, files in os.walk(file_dir,topdown=False):
        for name in files:
            # 只选择bmp jpg 
            # print(name.split('.')[-1])
            if name.split('.')[-1] in ['bmp','jpg','jpeg','png']:
                # print(os.path.join(root, name))
                filenames.append(os.path.join(root, name))
                img_name.append(name)
    return filenames,img_name

def cut_img(img_name,cut_points,save_path = './'):
    origin_img = cv2.imread(img_name)
    # cv2.imshow("img",origin_img)
    (filepath,tempfilename) = os.path.split(img_name)
    # print("img_name = {}".format(img_name))

    for i,points in enumerate(cut_points):
        tmp_img = origin_img[points[1]:points[3], points[0]:points[2]]
        tmp_path = os.path.join(save_path,tempfilename)         
        cv2.imwrite(tmp_path,tmp_img)



if __name__=='__main__':
    img_info = json_dict('./spray_roi.json')

    # 循环每个场景进行裁剪
    for item in img_info.keys():
        # 从指定文件夹内获取原始图片 并裁剪保存
        imgs_path,imgs_name = _getFilesPath(img_info[item]['file_path'])
        img_name = []
        for i,img in enumerate(imgs_path):
            if len(img_info[item]['ROI']) < 4:
                break
            points = img_info[item]['ROI']
            cut_img(img,points,img_info[item]['save_path'])

    pass